<?php

namespace admin\controllers;

use ijony\helpers\Utils;
use Yii;

/**
 * Class AjaxController
 * @package admin\controllers
 */
class AjaxController extends BaseController
{

    /**
     * @param $model
     * @param $field
     *
     * @return array
     */
    public function actionToggle()
    {
        $id = Yii::$app->request->post('id');
        $model = Yii::$app->request->post('model');
        $field = Yii::$app->request->post('field');

        Yii::$app->getResponse()->format = 'json';

        $model = ucfirst($model);
        $modelClass = '\\admin\\models\\' . $model;

        if (!class_exists($modelClass)) {
            return [
                'error' => 1,
            ];
        }

        /** @var \yii\db\ActiveRecord $model */
        $model = $modelClass::findOne($id);

        if (!$model->hasAttribute($field)) {
            return [
                'error' => 2,
            ];
        }

        if ($model->$field) {
            $model->$field = 0;
            $class = 'label-danger';
            $text = '禁用';
        } else {
            $model->$field = 1;
            $class = 'label-primary';
            $text = '启用';
        }

        if (!$model->save()) {
            return [
                'error' => 3,
            ];
        }

        return [
            'error' => 0,
            'html' => Utils::label($text, $class),
        ];
    }
}
